package shop.core.common.oscache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import shop.core.plugins.wxlogin.AccessToken;
import shop.core.plugins.wxlogin.WxContainer;
import shop.core.plugins.wxlogin.WxUrlType;
import shop.core.plugins.wxlogin.WxUtil;
import shop.services.manage.systemSetting.SystemSettingService;
import shop.services.manage.systemSetting.bean.SystemSetting;
import shop.services.manage.task.TaskService;
import shop.services.manage.task.bean.Task;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 缓存管理器。 后台项目可以通过接口程序通知该类重新加载部分或全部的缓存
 * 
 * @author huangf
 * 
 */
public class ManageCache {
	private static final Logger logger = LoggerFactory.getLogger(ManageCache.class);
	
	/**
	 * manage后台
	 */
    @Resource(name = "taskServiceManage")
	private TaskService taskService;
    @Autowired
    private SystemSettingService systemSettingService;
    @Autowired
    private SystemManager systemManager;
    @Value(value="classpath:area.json")
    private org.springframework.core.io.Resource data;


    /**
	 * 加载全部的缓存数据
	 * @throws Exception 
	 */
	public void loadAllCache() throws Exception {
		logger.error("ManageCache.loadAllCache...");
        loadSystemSetting();
        loadTask();
        loadAreaData();
		logger.error("后台缓存加载完毕!");
	}

    /**
     * 加载地理区域数据
     */
    public void  loadAreaData(){
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            File file = data.getFile();
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {

        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        systemManager.setAreaData(buffer.toString());
    }
    /**
     * 加载系统配置信息
     */
    public void loadSystemSetting() {
        SystemSetting systemSetting = systemSettingService.selectOne(new SystemSetting());
        if (systemSetting == null) {
            throw new NullPointerException("未设置本地环境变量，请管理员在后台进行设置");
        }
        systemManager.setSystemSetting(systemSetting);
    }

    /**
     * 加载定时任务
     */
    public void  loadTask(){
        List<Task> list = taskService.selectList(null);
        for(Task task:list){
            try{
                taskService.addTask(task);
            }catch (Exception e){
                logger.error("加载定时任务异常"+e);
            }

        }

    }


    /**
     * 加载微信AccessToken
     */
    public void loadAccessToken()  {
        Map<String,String> params = new HashMap<String,String>();
        params.put("grant_type","client_credential");
        params.put("appid", WxContainer.appid);
        params.put("secret",WxContainer.secret);
        AccessToken accessToken = new AccessToken();
        accessToken = WxUtil.sendRequest(WxUrlType.tokenUrl, HttpMethod.GET, params, null, AccessToken.class);
        systemManager.setAccessToken(accessToken);
        logger.debug("定时微信AccessToken"+accessToken);
    }

    /**
     * 加载微信jsapi_ticket
     */
    public void loadJsapiTicket()  {
        Map<String, String> getUserInfoParams = new HashMap<>();
        getUserInfoParams.put("access_token",systemManager.getAccessToken().getAccess_token());
        getUserInfoParams.put("type","jsapi");
        Map<String, String> rs = WxUtil.sendRequest(WxUrlType.jsapiTicketUrl, HttpMethod.GET, getUserInfoParams, null, Map.class);
        systemManager.setJsapiTicket(rs.get("ticket"));
        logger.debug("定时获取微信JsapiTicket!"+rs.get("ticket"));
    }

}
